package com.wuliu.servlet;

import com.wuliu.dao.UserDAO;
import com.wuliu.dao.impl.UserDAOImpl;
import com.wuliu.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/view/register.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        String gender = req.getParameter("gender");
        boolean admin =Boolean.valueOf(req.getParameter("admin"));
        User user = new User(null, account, password, name, gender,admin);
//        System.out.println(user);
        UserDAO userDAO = new UserDAOImpl();
        User user1 = userDAO.findByAccount(account);
        if (user1 != null) {
            req.setAttribute("msg", "该账号已经存在");
            req.getRequestDispatcher("/WEB-INF/view/register.jsp").forward(req, resp);
            return;
        }

        userDAO.add(user);
        req.setAttribute("msg", "注册成功");
        resp.sendRedirect("/login");


    }
}
